﻿import {
  EventEmitter,
  Injector,
  Input,
  Output,
  Component,
  OnInit,
  ViewChild,
  ElementRef
} from '@angular/core';
import * as moment from 'moment';

@Component({
  selector: 'table-date-time',
  template: `
    <input
      #inputDate
      type="{{hasTime ? 'datetime-local' : 'date'}}"
      (change)="dateChange($event)"
      style="width: 100%"
    />
  `
})
export class TableDateTimeComponent implements OnInit {
  @ViewChild('inputDate') inputDate: ElementRef;

  @Input() hasTime = false;

  _selectedDate: moment.Moment = undefined;
  @Output() selectedDateChange = new EventEmitter();

  @Input()
  get selectedDate() {
    return this._selectedDate;
  }

  set selectedDate(val) {
    this._selectedDate = val;
  }

  constructor(injector: Injector) {}

  ngOnInit(): void {
    if (this.selectedDate) {
      $(this.inputDate.nativeElement).val(
        this.selectedDate.format('YYYY-MM-DD')
      );
    }
  }

  dateChange(val) {
    if ($(val.target).val()) {
      this.selectedDate = moment($(val.target).val());
      this.selectedDateChange.emit(moment($(val.target).val()));
    }
  }
}
